package com.zzx.threekingdom.view;


import com.zzx.threekingdom.card.Card;
import com.zzx.threekingdom.card.CardList;
import com.zzx.threekingdom.resmanager.ResBitmapLib;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;

public class PlayerCardView extends ViewGroup
{
    public interface SelectCardsListener
    {
        void onSelectCard(CardList cards);
        void onSelectCard(ArrayList<CardView> cards);
        void onSelectSingleCard(Card card);
    }
    public boolean downIsPressed = false;
    public CardView downCardView = null;
    public boolean singleSelectMode = true;
    public ArrayList<CardView> mSelectedViews = new ArrayList<CardView>();
    private Rect mTouchFrame = new Rect();
    private final static int SELECTED_UP = -30;
    private SelectCardsListener mListener = null;
    private int mMultiSelectNumLimit = -1;
    private MyNotifyHandler mNotifyHandler = new MyNotifyHandler();
    private boolean bDitherOn = false;
    
    public PlayerCardView(Context context)
    {
        this(context, (AttributeSet)null);
    }
    public PlayerCardView(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }
    public PlayerCardView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        setMinimumWidth(ResBitmapLib.CARD_WIDTH*2);
        setMinimumHeight(ResBitmapLib.CARD_HEIGHT + 2 + Math.abs(SELECTED_UP));
        mSelectedViews.clear();
    }
    
    public void setSingleSelectMode(boolean bSet, int numLimit)
    {
        unselectAll();
        singleSelectMode = bSet;
        mMultiSelectNumLimit = numLimit;
    }
    
    public void addCards(CardList c)
    {
        checkChildren();
        for(int i = 0;i < c.size();i++)
        {
            addView(new CardView(getContext(), c.get(i)));
        }
        
    }
    
    public void removeCards(CardList c)
    {
        checkChildren();
       
        for(int i = 0;i < c.size();i++)
        {
            removeCard(c.get(i));
        }
    }
    public void removeCard(Card c)
    {
        checkChildren();
        for(int i = 0;i < getChildCount();i++)
        {
            View view = getChildAt(i);
            if(view instanceof CardView)
            {
                if(((CardView)view).getCard()==c)
                    removeViewAt(i--);
            }
        }
    }
    
    public void checkChildren()
    {
        for (int i = 0; i < getChildCount(); i++)
        {
            final View child = getChildAt(i);
            if(!(child instanceof CardView))
                removeViewAt(i--);
        }
    }
    
    public void clearView()
    {
        for (int i = 0; i < getChildCount(); i++)
        {
            final View child = getChildAt(i);
            if(child instanceof CardView)
                removeViewAt(i--);
        }
        bDitherOn = false;
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        checkChildren();
        final int freeSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        
        for (int i = 0; i < getChildCount(); i++)
        {
            getChildAt(i).measure(freeSpec, freeSpec);
        }
        setMeasuredDimension(MyViewGroupMeasure.getMeasure(widthMeasureSpec, getSuggestedMinimumWidth())
                , MyViewGroupMeasure.getMeasure(heightMeasureSpec, getSuggestedMinimumHeight()));
        
    }
    @Override
    public void addView(View child, int index, LayoutParams params)
    {
        if(child instanceof CardView)
        {
            super.addView(child, index, params);
            child.setEnabled(false);
        }
    }
    @Override
    public boolean onTouchEvent (MotionEvent event)
    {
        CardView pointedCard = null;
        int action = event.getAction();
        switch(action)
        {
            case MotionEvent.ACTION_DOWN:
                pointedCard = pointToView((int)event.getX(), (int)event.getY());
                if(pointedCard!=null)
                {
                    downCardView = pointedCard;
                    selectCard(downCardView);
                }
                break;
                
            case MotionEvent.ACTION_MOVE:
                pointedCard = pointToView((int)event.getX(), (int)event.getY());
                if((pointedCard!=null) && (downCardView!=pointedCard))
                {
                    selectCard(pointedCard);
                }
                downCardView = pointedCard;
                
                break;
            case MotionEvent.ACTION_UP:
                downCardView = null;
                break;
            default:
                break;
        }
        return true;
    }
    
    @Override
    protected void onLayout (boolean changed, int l, int t, int r, int b)
    {
        checkChildren();
        if(getChildCount()==0)
            return;
        
        final int height = getBottom() - getTop();
        int childLeft = getPaddingLeft();
        
        int childrenMaxWidth = 0;
        int childrenMaxHeight = 0;
        
        for (int i = 0; i < getChildCount(); i++)
        {
            final View child = getChildAt(i);
            childrenMaxWidth += child.getMeasuredWidth(); 
            childrenMaxHeight += child.getMeasuredHeight();
        }
        
        int measuredWidth = getMeasuredWidth(); 
       
        if(measuredWidth>=childrenMaxWidth)
        {
            for (int i = 0; i < getChildCount(); i++)
            {
                final View child = getChildAt(i);

                final int childWidth = child.getMeasuredWidth();
                final int childHeight = child.getMeasuredHeight();
                
                child.layout(childLeft, height - childHeight, childLeft + childWidth, height);
                childLeft += childWidth;
            }
        }
        else
        {
            int lastChildWidth = getChildAt(getChildCount() - 1).getMeasuredWidth();
            childLeft = measuredWidth - lastChildWidth;
            if(childLeft<0)
                return;
            int interval = childLeft/(getChildCount() - 1);
            
            for (int i = getChildCount() - 1; i > 0; i--)
            {
                final View child = getChildAt(i);
                int childWidth = child.getMeasuredWidth();
                final int childHeight = child.getMeasuredHeight();
                
                child.layout(childLeft, height - childHeight, childLeft + childWidth, height);
                childLeft -= interval;
            }
        }
    }
    
    public void selectCard(CardView card)
    {
       
        checkChildren();
        if(indexOfChild(card)==-1)
            return;
        if(mSelectedViews.contains(card))
        {
            unselectCard(card);
            return;
        }
        if(singleSelectMode==true)
            unselectAll();
        else if(mMultiSelectNumLimit>0)
        {
            int limit = mMultiSelectNumLimit - 1;
            while(mSelectedViews.size() > limit)
            {
                unselectCard(mSelectedViews.get(0));
            }
        }
        else if(mMultiSelectNumLimit==0)
            return;
        
        mSelectedViews.add(card);
        card.offsetTopAndBottom(SELECTED_UP);
        invalidate();
        notifyListener();
    }
    
    public void unselectAll()
    {
        checkChildren();
        if(mSelectedViews.size()!=0)
            notifyListener();
        for(int i = 0;i < mSelectedViews.size();i++)
        {
            mSelectedViews.get(i).offsetTopAndBottom(-SELECTED_UP);
        }
        mSelectedViews.clear();
        invalidate();
        
    }
    
    public void unselectCard(CardView card)
    {
        checkChildren();
        if(mSelectedViews.contains(card)==true)
        {
            card.offsetTopAndBottom(-SELECTED_UP);
            mSelectedViews.remove(card);
            notifyListener();
        }
        invalidate();
        
    }
    
    public void setEnabledAll(boolean enabled)
    {
        unselectAll();
        for(int i = 0;i < getChildCount();i++)
        {
            getChildAt(i).setEnabled(enabled);
        }
        invalidate();
    }
    
    public ArrayList<CardView> getSelectedCardViews() { return mSelectedViews; }
    public CardList getSelectedCards()
    {
        CardList cards = new CardList();
        ArrayList<CardView> cv = getSelectedCardViews();
        for(int i = 0;i < cv.size();i++)
        {
            cards.add(cv.get(i).getCard());
        }
        return cards;
    }
    
    public Card getSingleSelectedCard()
    {
        if((singleSelectMode==true)&&(mSelectedViews.size()>0))
            return mSelectedViews.get(0).getCard();
        return null;
    }
    
    public void setSelectListener(SelectCardsListener listener) { mListener = listener; }
    public void notifyListener()
    {
        mNotifyHandler.notifyListener();
    }
    
    public void drawCard(CardView card) { removeView(card); }
    
    
    public CardView pointToView(int x, int y)
    {
        checkChildren();
        final int count = getChildCount();
        for (int i = count - 1; i >= 0; i--)
        {
            View child = getChildAt(i);
            
            if((child.getVisibility() == View.VISIBLE)&&(child instanceof CardView)&&(child.isEnabled()==true))
            {
                //child.getHitRect(mTouchFrame);
                if(x>child.getLeft()&&x<child.getRight())
                    return (CardView)child;
            }
        } 
        return null;
    }
    
    
    private class MyNotifyHandler extends NotifyHandler
    {
        public void onNotify()
        {
            if(mListener!=null)
            {
                CardList cards = getSelectedCards();
                mListener.onSelectCard(cards);
                mListener.onSelectCard(getSelectedCardViews());
                int size = cards.size();
                mListener.onSelectSingleCard((size > 0)?cards.get(size - 1):null);
            }
        }

    }
    
    

}
